package org.szy.core.common.uilts;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.net.Ipv4Util;
import cn.hutool.core.util.ObjectUtil;
import org.lionsoul.ip2region.xdb.Searcher;
import org.noear.solon.core.handle.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.InputStream;

/**
 * 根据ip地址定位工具类，离线方式 参考地址：https://gitee.com/lionsoul/ip2region/tree/master/binding/java
 *
 * @author wangbuhao
 * @date 2023-02-09
 * @since 1.0.0
 **/
public class IpAddressUtil {

    private static final String LOCAL_REMOTE_HOST = "0:0:0:0:0:0:0:1";
    private static final Logger log = LoggerFactory.getLogger(IpAddressUtil.class);

    private static Searcher searcher = null;

    static {
        init();
    }

    public static void init() {
        String fileName = "/ip2region.xdb";
        File existFile = FileUtil.file(FileUtil.getTmpDir() + FileUtil.FILE_SEPARATOR + fileName);
        if (!FileUtil.exist(existFile)) {
            InputStream resourceAsStream = IpAddressUtil.class.getResourceAsStream(fileName);
            if (ObjectUtil.isEmpty(resourceAsStream)) {
                log.error("IpAddressUtil初始化失败，原因：IP地址库数据不存在");
                return;
            }
            FileUtil.writeFromStream(resourceAsStream, existFile);
        }

        String dbPath = existFile.getPath();

        // 1、从 dbPath 加载整个 xdb 到内存。
        byte[] cBuff;
        try {
            cBuff = Searcher.loadContentFromFile(dbPath);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("IpAddressUtil初始化失败，原因：{}", e.getMessage());
            return;
        }

        // 2、使用上述的 cBuff 创建一个完全基于内存的查询对象。
        try {
            searcher = Searcher.newWithBuffer(cBuff);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("IpAddressUtil初始化失败，原因：{}", e.getMessage());
        }
    }

    /**
     * 获取客户端ip
     *
     * @author wangbuhao
     * @date 2020/3/19 9:32
     */
    public static String getIp(Context request) {
        if (ObjectUtil.isEmpty(request)) {
            return Ipv4Util.LOCAL_IP;
        } else {
            try {
                String remoteHost = request.realIp();
                return LOCAL_REMOTE_HOST.equals(remoteHost) ? Ipv4Util.LOCAL_IP : remoteHost;
            } catch (Exception e) {
                e.printStackTrace();
                return Ipv4Util.LOCAL_IP;
            }
        }
    }

    /**
     * 根据IP地址离线获取城市
     *
     * @author wangbuhao
     * @date 2022/4/27 23:14
     */
    public static String getCityInfo(String ip) {
        try {
            ip = ip.trim();
            // 3、执行查询
            String region = searcher.search(ip);
            return region.replace("0|", "").replace("|0", "");
        } catch (Exception e) {
            return "未知";
        }
    }

}
